package com.bawei.module_live
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.MediaItem
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_net.RetrofitFactory
import com.bawei.module_live.adapter.GiftAdapter
import com.bawei.module_live.databinding.ActivityLiveDetailBinding
import com.bawei.module_live.intent.LiveIntent
import com.bawei.module_live.state.LiveState
import com.bawei.module_live.version1.GiftApi
import com.bawei.module_live.version1.GiftEntity
import com.bawei.module_live.version1.GoodsEntity
import com.bawei.module_live.version1.HourRankEntity
import com.bawei.module_live.version2.danmu.DanmakuWebSocketClient
import com.bawei.module_live.viewmodel.LiveViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMChatRoom
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import kotlinx.coroutines.launch
import com.bawei.module_live.version2.adapter.ImAdapter
import com.bawei.module_live.version2.mvi.model.entity.ImEntity
import com.hyphenate.EMMessageListener
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGAImageView
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.tencent.mmkv.MMKV
import okhttp3.ResponseBody
import java.io.File
import java.net.URL
import com.bumptech.glide.Glide
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST

// 关注接口API
interface FollowApi {
    @FormUrlEncoded
    @POST("/focuse/focuse")
    suspend fun focusUser(
        @Field("focuseUserid") focuseUserid: String,
        @Field("focusedUserid") focusedUserid: String
    ): FocusResponse
}

data class FocusResponse(val code: Int, val msg: String, val data: Boolean)


@Route(path = "/module_live/LiveDetailActivity")
class LiveDetailActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLiveDetailBinding
    private lateinit var player: ExoPlayer
    lateinit var countDownTimer: CountDownTimer
    private lateinit var playerView: PlayerView
    var favNum = 1302
    var time = 0L
    private lateinit var viewModel: LiveViewModel
    private lateinit var danmakuView: master.flame.danmaku.ui.widget.DanmakuView
    private lateinit var danmakuContext: master.flame.danmaku.danmaku.model.android.DanmakuContext
    private lateinit var webSocketClient: DanmakuWebSocketClient
//    private val userId = 2355 // 当前用户id
    private var isFollowed = false // 默认未关注
    private var userId: String? = MMKV.defaultMMKV().decodeString("userId") // 当前用户id

    private lateinit var adapter: ImAdapter
    private val chatRoomId = "285714979815427"
    private val imlist = arrayListOf<ImEntity>()
    private lateinit var svgaImageView: SVGAImageView


    private val imMessageListener = object : EMMessageListener {
        override fun onMessageReceived(messages: List<EMMessage>?) {
            messages?.forEach { msg ->
                if (msg.to == chatRoomId && msg.type == EMMessage.Type.TXT) {
                    val body = msg.body as EMTextMessageBody
                    val nickname = msg.getStringAttribute("nickname", msg.from)
                    runOnUiThread { addMessageToList(nickname, body.message) }
                }
            }
        }

        override fun onCmdMessageReceived(messages: List<EMMessage>?) {}
        override fun onMessageRead(messages: List<EMMessage>?) {}
        override fun onMessageDelivered(messages: List<EMMessage>?) {}
        override fun onMessageRecalled(messages: List<EMMessage>?) {}
        override fun onMessageChanged(message: EMMessage?, change: Any?) {}
    }

    @OptIn(UnstableApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLiveDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        svgaImageView = binding.svgaImageView

        viewModel = ViewModelProvider(this)[LiveViewModel::class.java]
        lifecycleScope.launch {
            viewModel.liveFlow_.collect { state ->
                when (state) {
                    is LiveState.GoodsListSuccess -> {
                        showGoodsDialog(state.data)
                    }

                    is LiveState.GoodsListFailed -> {
                        Toast.makeText(
                            this@LiveDetailActivity,
                            "获取商品失败: ${state.message}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    else -> {}
                }
            }
        }

        val videoPath = intent.getStringExtra("videoPath") ?: ""
        val videoTitle = intent.getStringExtra("videoTitle") ?: ""
        val videoName = intent.getStringExtra("videoName") ?: ""
        val videoAvatar = intent.getStringExtra("videoAvatar") ?: ""
        val videoProgress = intent.getLongExtra("videoProgress", 0L)
        val anchorId = intent.getStringExtra("anchorId") ?: "" // 主播id
        val userId = MMKV.defaultMMKV().decodeString("userId")   // 当前用户id
        val roomId = intent.getStringExtra("roomId") ?: "" // 新增：直播间id

        binding.liveDetailAuthorName.text = videoName
        // 设置头像
        Glide.with(this)
            .load(videoAvatar)
            .placeholder(R.mipmap.ic_launcher)
            .circleCrop()
            .into(binding.liveDetailAuthorIcon)

        playerView = binding.playerView
        player = ExoPlayer.Builder(this)
            .setSeekBackIncrementMs(5000) // 快退步长5秒
            .setSeekForwardIncrementMs(5000) // 快进步长5秒
            .build()

        playerView.player = player
        val mediaItem = MediaItem.fromUri(videoPath)
        player.setMediaItem(mediaItem)
        player.prepare()
        player.play()
        binding.klv.addLikeImages(
            R.drawable.fav_0,
            R.drawable.fav_1,
            R.drawable.fav_2,
            R.drawable.fav_3,
            R.drawable.fav_4,
            R.drawable.fav_5
        )
        binding.liveDetailFav.setOnClickListener {
            binding.klv.addFavor()
            ++favNum
            binding.liveDetailAuthorLikeNum.text = "${favNum}本场点赞"
        }
        //红包倒计时
        countDownTimer = object : CountDownTimer(10000, 1000) {
            override fun onTick(p0: Long) {
                time = p0
                val simpleDateFormat = java.text.SimpleDateFormat("mm:ss")
                val s = simpleDateFormat.format(p0)
                binding.redEnvelopeTime.text = s
            }

            override fun onFinish() {
                binding.redEnvelopeTime.visibility = View.GONE
                binding.redEnvelope.visibility = View.GONE
            }
        }.start()

        initDanmaku()

        val itemId = "6936590061114753549"
        // 2. 连接WebSocket，实时弹幕
        webSocketClient = DanmakuWebSocketClient(
            wsUrl = "ws://10.161.9.80:7015/api/danmu/websocket/$itemId",
            onDanmakuReceived = { text, color ->
                runOnUiThread { addDanmaku(text, color) }
            }
        )
        webSocketClient.connect()


        // 1. 初始化RecyclerView和Adapter
        adapter = ImAdapter()
        binding.imRv.layoutManager = LinearLayoutManager(this)
        binding.imRv.adapter = adapter

        // 2. 加入环信聊天室
        EMClient.getInstance().chatroomManager()
            .joinChatRoom(chatRoomId, object : EMValueCallBack<EMChatRoom> {
                override fun onSuccess(value: EMChatRoom?) {
                    runOnUiThread { showToast("加入聊天室成功") }
                }

                override fun onError(error: Int, errorMsg: String?) {
                    runOnUiThread { showToast("加入聊天室失败: $errorMsg") }
                }
            })

        // 3. 注册消息监听（放在onCreate里！）
        EMClient.getInstance().chatManager().addMessageListener(imMessageListener)

        val account = MMKV.defaultMMKV().decodeString("account")
        // 4. 发送消息
        binding.sendBarrage.setOnClickListener {

            val content = binding.commentContent.text.toString().trim()
            if (content.isNotEmpty()) {
                // 发送弹幕
                webSocketClient.sendDanmaku(
                    text = content,
                    color = "#00f0ff",
                    itemid = itemId,
                    userid = userId!!
                )
                // 发送环信消息
                val message = EMMessage.createTxtSendMessage(content, chatRoomId)
                message.chatType = EMMessage.ChatType.ChatRoom
                message.setAttribute("nickname", account)
                EMClient.getInstance().chatManager().sendMessage(message)
                // 本地显示
                addMessageToList(account!!, content)
                binding.commentContent.setText("")
            }
        }

        // 关注按钮初始化
        updateFollowButton()
        binding.liveDetailFollow.setOnClickListener {
            isFollowed = !isFollowed
            updateFollowButton()
        }
        // 关闭按钮点击事件
        binding.liveDetailClose.setOnClickListener {
            finish()
        }
        // 礼物按钮点击事件
        binding.gift.setOnClickListener {
            lifecycleScope.launch {
                try {
                    val api = RetrofitFactory.getRetrofitFactory().create(GiftApi::class.java)
                    val response = api.getGiftList()
                    if (response.code == 200) {
                        showGiftDialog(response.data)
                    } else {
                        Toast.makeText(this@LiveDetailActivity, "获取礼物失败", Toast.LENGTH_SHORT)
                            .show()
                    }
                } catch (e: Exception) {
                    Toast.makeText(this@LiveDetailActivity, "网络异常", Toast.LENGTH_SHORT).show()
                }
            }
        }
        // 商品按钮点击事件
        binding.openGoods.setOnClickListener {
            lifecycleScope.launch {
                viewModel.intents.send(LiveIntent.GetGoodsList(0, 1, 10, 1))
            }
        }
        // 小时榜按钮点击事件
        binding.hourList.setOnClickListener {
            showHourRankDialog()
        }
        // 红包点击事件
        binding.redEnvelope.setOnClickListener {
            val dialog = com.bawei.module_live.ui.dialog.RedPacketDialogFragment()
            dialog.listener =
                object : com.bawei.module_live.ui.dialog.RedPacketDialogFragment.RedPacketListener {
                    override fun onGrabbed() {
                        binding.redEnvelopeTime.text = "已抢完"
                        binding.redEnvelope.isEnabled = false
                        binding.redEnvelope.visibility = View.GONE
                        binding.redEnvelopeTime.visibility = View.GONE
                    }
                }
            dialog.show(supportFragmentManager, "RedPacketDialog")
        }

        binding.moreLive.setOnClickListener {
            ARouter.getInstance().build("/module_live/LiveingActivity").navigation()
        }

        // 新增：请求直播间在线人数并设置到TextView
        lifecycleScope.launch {
            try {
                val api = com.bawei.lib_net.RetrofitFactory.getRetrofitFactory().create(com.bawei.module_live.version2.mvi.model.api.LiveApi::class.java)
                val response = api.getLiveRoomUsers(roomId)
                if (response.code == 200 && response.data != null) {
                    val onlineCount = response.data.size
                    binding.audienceNum.text = onlineCount.toString()
                } else {
                    binding.audienceNum.text = "0"
                }
            } catch (e: Exception) {
                binding.audienceNum.text = "0"
            }
        }


    }
    private fun addMessageToList(name: String, content: String) {
        imlist.add(ImEntity(name, content))
        adapter.updateData(imlist)
        binding.imRv.scrollToPosition(imlist.size - 1)
    }

    private fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    private fun initDanmaku() {
        danmakuView = findViewById(R.id.dv)
        danmakuContext = master.flame.danmaku.danmaku.model.android.DanmakuContext.create()
        danmakuView.setCallback(object : master.flame.danmaku.controller.DrawHandler.Callback {
            override fun prepared() {
                danmakuView.start()
            }

            override fun updateTimer(timer: master.flame.danmaku.danmaku.model.DanmakuTimer?) {}
            override fun danmakuShown(danmaku: master.flame.danmaku.danmaku.model.BaseDanmaku?) {}
            override fun drawingFinished() {}
        })
        danmakuView.prepare(object : master.flame.danmaku.danmaku.parser.BaseDanmakuParser() {
            override fun parse() = master.flame.danmaku.danmaku.model.android.Danmakus()
        }, danmakuContext)
        danmakuView.enableDanmakuDrawingCache(true)
    }

    private fun addDanmaku(text: String, color: Int) {
        val danmaku =
            danmakuContext.mDanmakuFactory.createDanmaku(master.flame.danmaku.danmaku.model.BaseDanmaku.TYPE_SCROLL_RL)
        danmaku?.apply {
            this.text = text
            this.textColor = color
            this.textSize = 48f
            this.setTime(danmakuView.currentTime + 500)
            this.isLive = true
        }
        danmakuView.addDanmaku(danmaku)
    }

    override fun onDestroy() {
        countDownTimer.cancel() // 1. 取消计时器
        webSocketClient.disconnect() // 2. 断开WebSocket（内部已清理回调）
        danmakuView.release() // 3. 释放弹幕资源
        player.release() // 4. 释放播放器
        // 移除消息监听
        EMClient.getInstance().chatManager().removeMessageListener(imMessageListener)
        // 释放SVGAImageView资源，防止内存泄漏
        svgaImageView.stopAnimation(true)
        svgaImageView.setVideoItem(null)
        super.onDestroy()
    }

    override fun onPause() {
        super.onPause()
        player.pause()
    }

    // 展示礼物弹窗
    private fun showGiftDialog(giftList: List<GiftEntity>) {
        val dialog = BottomSheetDialog(this)
        val view = layoutInflater.inflate(R.layout.dialog_gift_list, null)
        val rv = view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.rv_gift)
        rv.layoutManager = GridLayoutManager(this, 4)
        rv.adapter = GiftAdapter(giftList) { gift ->
            lifecycleScope.launch {
                try {
                    Log.d("Gift", "svgaPath = ${gift.svgaPath}")
                    // 每次播放前先停止并清空上一个动画
                    svgaImageView.stopAnimation(true)
                    svgaImageView.setVideoItem(null)
                    if (gift.svgaPath.startsWith("http")) {
                        val parser = SVGAParser(this@LiveDetailActivity)
                        parser.decodeFromURL(URL(gift.svgaPath), object : SVGAParser.ParseCompletion {
                            override fun onComplete(videoItem: SVGAVideoEntity) {
                                svgaImageView.visibility = View.VISIBLE
                                svgaImageView.setVideoItem(videoItem)
                                svgaImageView.loops = 1 // 只播放一次
                                svgaImageView.startAnimation()
                                svgaImageView.callback = object : SVGACallback {
                                    override fun onFinished() {
                                        svgaImageView.visibility = View.GONE
                                        svgaImageView.setVideoItem(null)
                                    }
                                    override fun onPause() {}
                                    override fun onRepeat() {}
                                    override fun onStep(frame: Int, percentage: Double) {}
                                }
                            }
                            override fun onError() {
                                Toast.makeText(this@LiveDetailActivity, "动画解析失败", Toast.LENGTH_SHORT).show()
                                svgaImageView.visibility = View.GONE
                                svgaImageView.setVideoItem(null)
                            }
                        })
                    } else {
                        val filename = gift.svgaPath.removeSuffix(".svga")
                        Log.d("Gift", "downloadSvga filename = $filename")
                        val api = RetrofitFactory.getRetrofitFactory().create(com.bawei.module_live.gift.GiftApi::class.java)
                        val responseBody: ResponseBody = api.downloadSvga(filename)
                        val file = File(cacheDir, "$filename.svga")
                        file.outputStream().use { output ->
                            responseBody.byteStream().copyTo(output)
                        }
                        playSvga(file)
                    }
                } catch (e: Exception) {
                    Log.e("Gift", "Exception: ", e)
                    Toast.makeText(this@LiveDetailActivity, "动画加载失败", Toast.LENGTH_SHORT).show()
                }
            }
            dialog.dismiss()
        }
        dialog.setContentView(view)
        dialog.setOnDismissListener {
            // 重置ViewModel状态，保证下次点击还能弹出
            viewModel.resetState()
        }
        dialog.show()
        dialog.window?.apply {
            setGravity(Gravity.START or Gravity.CENTER_VERTICAL)
            setLayout(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }
    // 播放SVGA动画
    private fun playSvga(file: File) {
        svgaImageView.stopAnimation(true)
        svgaImageView.setVideoItem(null)
        svgaImageView.visibility = View.VISIBLE
        val parser = SVGAParser(this)
        parser.decodeFromInputStream(file.inputStream(), file.name, object : SVGAParser.ParseCompletion {
            override fun onComplete(videoItem: SVGAVideoEntity) {
                svgaImageView.setVideoItem(videoItem)
                svgaImageView.loops = 1 // 只播放一次
                svgaImageView.startAnimation()
                svgaImageView.callback = object : SVGACallback {
                    override fun onFinished() {
                        svgaImageView.visibility = View.GONE
                        svgaImageView.setVideoItem(null)
                    }
                    override fun onPause() {}
                    override fun onRepeat() {}
                    override fun onStep(frame: Int, percentage: Double) {}
                }
            }
            override fun onError() {
                Toast.makeText(this@LiveDetailActivity, "动画解析失败", Toast.LENGTH_SHORT).show()
                svgaImageView.visibility = View.GONE
                svgaImageView.setVideoItem(null)
            }
        }, true)
    }

    // 展示商品弹窗
    private fun showGoodsDialog(goodsList: List<GoodsEntity>) {
        val dialog = BottomSheetDialog(this)
        val view = layoutInflater.inflate(R.layout.dialog_goods_list, null)
        val rv = view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.rv_goods)
        rv.layoutManager = GridLayoutManager(this, 2)
        rv.adapter = com.bawei.module_live.adapter.GoodsAdapter(goodsList) { goods ->
            Toast.makeText(this, "选择了: ${goods.goods_desc}", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }
        dialog.setContentView(view)
        dialog.setOnDismissListener {
            // 重置ViewModel状态，保证下次点击还能弹出
            viewModel.resetState()
        }
        dialog.show()
        dialog.window?.apply {
            setGravity(Gravity.START or Gravity.CENTER_VERTICAL)
            setLayout(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }

    // 展示小时榜弹窗
    private fun showHourRankDialog() {
        val dialog = android.app.Dialog(this, android.R.style.Theme_Translucent_NoTitleBar)
        val view = layoutInflater.inflate(R.layout.dialog_hour_rank, null)
        val rv = view.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.rv_hour_rank)
        rv.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        val data = listOf(
            HourRankEntity(R.drawable.fav_0, "杨子东", "鞋靴箱包", 12),
            HourRankEntity(R.drawable.fav_1, "王永安", "服饰内衣", 10),
            HourRankEntity(R.drawable.fav_2, "张庭瑜", "食品饮料", 8),
            HourRankEntity(R.drawable.fav_3, "贾朝阳", "综合", 7),
            HourRankEntity(R.drawable.fav_4, "李晓明", "食品饮料", 6)
        )
        rv.adapter = com.bawei.module_live.adapter.HourRankAdapter(data)
        dialog.setContentView(view)
        // 设置左滑动画
        view.translationX = -400f
        view.animate().translationX(0f).setDuration(300).start()
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        // 设置弹窗宽度和左侧gravity
        dialog.window?.apply {
            setGravity(Gravity.START or Gravity.CENTER_VERTICAL)
            setLayout(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
        // 点击遮罩关闭，先动画再dismiss
        val mask = view.findViewById<View>(R.id.close_mask)
        val content = view.findViewById<View>(R.id.hour_rank_content)
        mask.setOnClickListener {
            content.animate()
                .translationX(-400f)
                .setDuration(300)
                .withEndAction { dialog.dismiss() }
                .start()
        }
    }
    override fun onResume() {
        super.onResume()
        if (binding.dv != null && binding.dv.isPrepared() && binding.dv.isPaused()) {
            binding.dv.resume();
        }
    }

    private fun updateFollowButton() {
        if (isFollowed) {
            binding.liveDetailFollow.text = "已关注"
            binding.liveDetailFollow.isSelected = true
            //binding.liveDetailFollow.setTextColor(Color.GRAY)
        } else {
            binding.liveDetailFollow.text = "关注"
            binding.liveDetailFollow.isSelected = false
            binding.liveDetailFollow.setTextColor(resources.getColor(R.color.black))
        }
    }

    private fun doFollow(userId: String, anchorId: String) {
        Log.d("FollowDebug", "doFollow called, userId=$userId, anchorId=$anchorId")
        lifecycleScope.launch {
            try {
                val api = RetrofitFactory.getRetrofitFactory().create(FollowApi::class.java)
                Log.d("FollowDebug", "API created, about to call focusUser")
                val response = api.focusUser(userId, anchorId)
                Log.d("FollowDebug", "API response: code=${response.code}, msg=${response.msg}, data=${response.data}")
                if (response.code == 200 && response.data) {
                    isFollowed = true
                    updateFollowButton()
                    Toast.makeText(this@LiveDetailActivity, "关注成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@LiveDetailActivity, response.msg ?: "关注失败", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Log.e("FollowDebug", "关注异常: ${e.message}", e)
                Toast.makeText(this@LiveDetailActivity, "网络异常: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}